package com.jason.practice.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

@Slf4j
public class SpringRestUtils {

    public static <T> T postWithJson(String url, JSONObject param, Class<T> responseType) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        // 设置ContentType
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 请求
        return postWithJson(url, headers, param, responseType);
    }

    public static <T> T postWithJson(String url, HttpHeaders headers, JSONObject param, Class<T> responseType) {
        // 请求
        return postWithJson(url, headers, param.toString(), responseType);
    }

    public static <T> T postWithJson(String url, HttpHeaders headers, String param, Class<T> responseType) {
        // 设置ContentType
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 请求中设置param和headers
        HttpEntity<String> request = new HttpEntity<>(param, headers);
        // post请求并返回
        return getRestTemplate().postForObject(url, request, responseType);
    }

    public static <T> T getForObject(String url, Class<T> responseType) {
        // get请求并返回
        return getRestTemplate().getForObject(url, responseType);
    }


    public static String getForObject(String url, HttpHeaders headers) {
        // 设置ContentType
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 设置请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        // get请求获取响应内容
        ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, requestEntity, String.class);
        // 返回响应body
        return response.getBody();
    }


    public static String getForXml(String url, HttpHeaders headers) {
        // 设置ACCEPT
        headers.add("Accept", MediaType.APPLICATION_XML_VALUE);
        // 设置ContentType
        headers.setContentType(MediaType.APPLICATION_XML);
        // 设置请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        // get请求获取响应内容
        ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, requestEntity, String.class);
        // 返回响应body
        log.info(url + "&&&&&" + response.toString() + "&&&&&" + response.getBody());
        return response.getBody();
    }

    private static RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}